<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>2_引出生命周期（旧）</title>
  </head>
  <body>
    <div id="app"></div>
    <!-- 引入react核心库 -->
    <script src="../js/react.development.js"></script>
    <!-- 引入react-dom，用于支持react dom操作 -->
    <script src="../js/react-dom.development.js"></script>
    <!-- 引入babel，用于将jsx转为js -->
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">
      // 创建组件
      class MyComponent extends React.Component {
        constructor(props) {
          console.log('MyComponent--constructor')
          super(props)

          this.state = { count: 0 }
        }

        add = () => {
          const { count } = this.state
          this.setState({ count: count + 1 })
        }

        death = () => {
          ReactDOM.unmountComponentAtNode(document.getElementById('app'))
        }

        force = () => {
          this.forceUpdate()
        }

        // 组件即将挂载钩子
        componentWillMount() {
          console.log('MyComponent--componentWillMount')
        }

        // 组件挂载完成钩子
        componentDidMount() {
          console.log('MyComponent--componentDidMount')
        }

        // 组件即将卸载钩子
        componentWillUnmount() {
          console.log('MyComponent--componentWillUnmount')
        }

        // 组件是否应该更新钩子
        shouldComponentUpdate(nextProps, nextState) {
          console.log('MyComponent--shouldComponentUpdate')
          return true
        }

        // 组件即将更新钩子
        componentWillUpdate() {
          console.log('MyComponent--componentWillUpdate')
        }

        // 组件完成更新钩子
        componentDidUpdate() {
          console.log('MyComponent--componentDidUpdate')
        }

        render() {
          console.log('MyComponent--render')
          return (
            <div>
              <h2>当前求和为{this.state.count}</h2>
              <button onClick={this.add}>点我加1</button>
              <button onClick={this.death}>卸载组件</button>
              <button onClick={this.force}>强制更新组件</button>
            </div>
          )
        }
      }

      class A extends React.Component {
        state = { carName: '奔驰' }

        changeCar = () => {
          this.setState({ carName: '宝马' })
        }

        render() {
          return (
            <div>
              我是A组件
              <button onClick={this.changeCar}>换车</button>              
              <B carName={this.state.carName} />
            </div>
          )
        }
      }

      class B extends React.Component {
        // 子组件接收到新的属性才调用（即第二次渲染才调用）
        componentWillReceiveProps(nextProps) {
          console.log('B组件接受到新的属性：', nextProps)
        }

        render() {
          return <div>我是B组件，接收到的车是{this.props.carName}</div>
        }
      }

      // 渲染组件到DOM
      ReactDOM.render(<A />, document.getElementById('app'))
    </script>
  </body>
</html>
